package main

import (
	"fmt"
	"log"
	"strconv"
	"tone-agent/core"
	"tone-agent/entity"
	"tone-agent/router"
	"tone-agent/setup"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func main() {
	setup.ParseFlags()

	if setup.Debug {
		entity.Debug = true
		gin.SetMode(gin.DebugMode)
	} else {
		entity.Debug = false
	}

	if setup.ShowVersion {
		fmt.Println(entity.Version)
		return
	}

	if setup.ShowInfo {
		fmt.Println(fmt.Sprintf(entity.Prompts, entity.Version))
		return
	}

	gin.SetMode(entity.Mode)
	ta := gin.Default()

	setup.InitPath()
	setup.LoadConfig()
	setup.SetupLogger()

	ta.LoadHTMLGlob(entity.TemplatesPath + "/*")

	store := cookie.NewStore([]byte("tone-agent-secret-key"))
	ta.Use(sessions.Sessions("tone-agent", store))

	router.AdminRouter(ta)
	router.APIRouter(ta)

	if setup.HeartbeatTest {
		setup.HandleHeartbeatTest()
		return
	}
	if setup.ShowConfig {
		setup.HandleShowConfig()
		return
	}
	if setup.ShowLog {
		setup.HandleShowLog()
		return
	}
	if setup.Restart {
		setup.HandleRestart()
		return
	}
	if setup.Update {
		setup.HandleUpdate()
		return
	}
	if setup.Upgrade != "" {
		setup.HandleUpgrade()
		return
	}
	if setup.ShowVersionList {
		setup.HandleVersionList()
		return
	}
	if setup.SetTSN != "" {
		setup.HandleSetTSN()
		return
	}
	if setup.SetMode != "" {
		setup.HandleSetMode()
		return
	}
	if setup.SetProxy != "" {
		setup.HandleSetProxy()
	}

	core.RecoverTaskProcess()
	setup.InitCron()

	prompts := fmt.Sprintf(entity.Prompts, entity.Version)
	log.Print(prompts)
	log.Print("Service starting......\n\n")
	ta.Run(":" + strconv.Itoa(setup.Port))
}
